package com.duowei.dw_pos;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.duowei.dw_pos.bean.Auth;
import com.duowei.dw_pos.bean.DMJYXMSSLB;
import com.duowei.dw_pos.bean.YHJBQK;
import com.duowei.dw_pos.bean.Ygsbbc;
import com.duowei.dw_pos.dialog.ClearDialogFragment;
import com.duowei.dw_pos.dialog.MsgInputDialog;
import com.duowei.dw_pos.fragment.AuthDialogFragment;
import com.duowei.dw_pos.httputils.DownHTTP;
import com.duowei.dw_pos.httputils.VolleyResultListener;
import com.duowei.dw_pos.tools.CartList;
import com.duowei.dw_pos.tools.DataLoad;
import com.duowei.dw_pos.tools.Net;
import com.duowei.dw_pos.tools.PermissionsUtil;
import com.duowei.dw_pos.tools.Users;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.List;

import butterknife.ButterKnife;
public class LandActivity extends AppCompatActivity implements View.OnClickListener,
        MsgInputDialog.OnconfirmClick, CompoundButton.OnCheckedChangeListener {
    private SharedPreferences mSp;
    private EditText mEtAccount;
    private EditText mEtPassword;
    private Intent mIntent;
    private TextView mVersion;
    private String mOrderstytle;
    private MsgInputDialog mMsgInputDialog;
    public static int mVersionCode=0;
    public static String mVersionName;
    private boolean mClear;

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private ProgressBar mPb;
    private SharedPreferences.Editor mEdit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_land);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        ButterKnife.bind(this);
//        SQLiteStudioService.instance().start(this);
        mSp = getSharedPreferences("user", Context.MODE_PRIVATE);
        mEdit = mSp.edit();
        initUI();

        checkPermission();
        Auth auth = DataSupport.findFirst(Auth.class);
        if(auth==null||!"1".equals(auth.getIsforver())){
            AuthDialogFragment fragment = AuthDialogFragment.newInstance(auth);
            fragment.show(getSupportFragmentManager(),null);
            return;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mOrderstytle = mSp.getString("orderstytle", getResources().getString(R.string.order_stytle_zhongxican));
        mClear = mSp.getBoolean("clear", false);
        Users.pad=mSp.getString("pad","");
        Users.rounding=mSp.getString("rounding",getString(R.string.rounding_jiao));
        String ip = mSp.getString("ip", "");
        Net.url="http://"+ip+":2233/server/ServerSvlt?";

        //change 2018-04-12
        List<DMJYXMSSLB> list = DataSupport.select("lbbm").where("sfty != ? and lbbm != ?", "1", "RICH").order("xl").find(DMJYXMSSLB.class);
        if(list.size()<=0){
            DataLoad.getInstance().startLoad(this);
        }
    }

    private void initUI() {
        String yhbh = mSp.getString("yhbh", "");
        String password = mSp.getString("password", "");
        boolean savepassword = mSp.getBoolean("savepassword", false);
        mEtAccount = (EditText) findViewById(R.id.et_account);
        mEtPassword = (EditText) findViewById(R.id.et_password);
        mEtAccount.setText(yhbh);
        if(savepassword){
            mEtPassword.setText(password);
        }

        mVersion = (TextView) findViewById(R.id.tv_version);
        mPb = (ProgressBar) findViewById(R.id.progressBar);
        CheckBox checkBox = (CheckBox) findViewById(R.id.checkbox);
        checkBox.setChecked(savepassword);
        checkBox.setOnCheckedChangeListener(this);
        findViewById(R.id.tv_brush).setOnClickListener(this);
        findViewById(R.id.tv_setting).setOnClickListener(this);
        findViewById(R.id.btn_land).setOnClickListener(this);
        findViewById(R.id.btn_exit).setOnClickListener(this);
        mVersion.setText(getVersionName());
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_brush:
                DataLoad.getInstance().startLoad(this);
                break;
            case R.id.tv_setting:
                mMsgInputDialog = new MsgInputDialog(this, "请输入密码", "密码：");
                mMsgInputDialog.setOnconfirmClick(this);
                break;
            case R.id.btn_land:
                final String account = mEtAccount.getText().toString().trim();
                String password = mEtPassword.getText().toString().trim();
                final YHJBQK yhjbqk = DataSupport.where("YHBH=? and YHMM=?", account, password).findFirst(YHJBQK.class);
                if(yhjbqk==null){
                    Toast.makeText(this,"账号或密码错误",Toast.LENGTH_SHORT).show();
                }else{
                    if(mClear){//启用清机下班
                        mPb.setVisibility(View.VISIBLE);
                        String sql="select by6 from ygsbbc where xbsj is null and yhbh='"+account+"' and by6<>'"+Users.pad+"'|";
                        DownHTTP.postVolley6(Net.url, sql, new VolleyResultListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(LandActivity.this,"网络异常",Toast.LENGTH_SHORT).show();
                                mPb.setVisibility(View.GONE);
                            }
                            @Override
                            public void onResponse(String response) {
                                if(response.toLowerCase().contains("error")){
                                    Toast.makeText(LandActivity.this,response,Toast.LENGTH_SHORT).show();
                                    mPb.setVisibility(View.GONE);
                                    return;
                                }
                                if(response.equals("]")){
                                    Http_insertYgsbbc(account, yhjbqk);
                                }else{
                                    try {
                                        JSONObject jsonObject = new JSONArray(response).getJSONObject(0);
                                        String by6 = jsonObject.getString("by6");
                                        Toast.makeText(LandActivity.this,account+yhjbqk.getYHMC()+",己经在其它收银机(名称："+by6+")上登录",Toast.LENGTH_SHORT).show();
                                        mPb.setVisibility(View.GONE);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
                    }else{
                        toLand(yhjbqk);
                    }
                }
                break;
            case R.id.btn_exit:
                if(mClear&&!TextUtils.isEmpty(Users.pad)){
                    ClearDialogFragment fragment = ClearDialogFragment.newInstance(Users.pad,Users.YHBH,Users.YHMC);
                    fragment.show(getSupportFragmentManager(),null);
                }else{
                    finish();
                }
                break;
        }
    }

    private void Http_insertYgsbbc(String account, final YHJBQK yhjbqk) {
        String sql="if not exists (select * from ygsbbc where yhbh='"+account+"' and by6='"+ Users.pad+"' and (xbsj is null or xbsj=''))" +
                " insert into ygsbbc(yhbh,yhmc,sbrq,sbsj,by6)values('"+account+"','"+yhjbqk.YHMC+"',CONVERT(varchar(100), GETDATE(), 23),CONVERT(varchar(100), GETDATE(), 120),'"+Users.pad+"')|";
        DownHTTP.postVolley7(Net.url, sql, new VolleyResultListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(LandActivity.this,"网络异常",Toast.LENGTH_SHORT).show();
                mPb.setVisibility(View.GONE);
            }
            @Override
            public void onResponse(String response) {
                if(response.contains("richado")){
                    toLand(yhjbqk);
                    mPb.setVisibility(View.GONE);
                    Http_Ygsbbc();
                }
            }
        });
    }

    private void Http_Ygsbbc(){
        String sql="select y.yhbh,y.yhmc from ygsbbc y,xsjbxx x where " +
                "y.xbsj is null and y.yhmc in(select yhbh from wmlsbjb where sfyjz='1' and jsj='"+Users.pad+"' and isnull(by7,'0')<>'1') " +
                "and x.xh=y.yhbh and x.bz='"+Users.pad+"'and x.jysj between  y.sbsj and getdate() group by y.yhbh,y.yhmc|";
        DownHTTP.postVolley6(Net.url, sql, new VolleyResultListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Users.ygsbbcs=new Ygsbbc[]{new Ygsbbc(Users.YHBH,Users.YHMC)};
            }
            @Override
            public void onResponse(String response) {
               if(!response.equals("]")&&!response.toLowerCase().contains("error")){
                   Gson gson = new Gson();
                   Users.ygsbbcs=gson.fromJson(response, Ygsbbc[].class);
               }else{
                   Users.ygsbbcs=new Ygsbbc[]{new Ygsbbc(Users.YHBH,Users.YHMC)};
               }
            }
        });
    }

    private void toLand(YHJBQK yhjbqk) {
        Users.YHBH=yhjbqk.YHBH;
        Users.YHMC=yhjbqk.YHMC;
        Users.TDQX=yhjbqk.TDQX;
        mEdit.putString("yhbh",Users.YHBH);
        if(mSp.getBoolean("savepassword", false)){
            mEdit.putString("password",mEtPassword.getText().toString().trim());
        }
        mEdit.commit();

        if(mOrderstytle.equals(getResources().getString(R.string.order_stytle_zhongxican))){
            mIntent = new Intent(this, DinningActivity.class);
        }else if(mOrderstytle.equals(getResources().getString(R.string.order_stytle_kuaican))){
            mIntent = new Intent(this, CashierDeskActivity.class);
        }
        startActivity(mIntent);
    }

    private void checkPermission() {
        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
        PermissionsUtil.requestPermissions(this, PermissionsUtil.allPermissions);//校验权限
    }

    private String getVersionName() {
        try {
            PackageInfo info = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
            mVersionName = "版本号："+info.versionName;
            mVersionCode = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return mVersionName;
    }

    @Override
    public void getDialogInput(String contents) {
        if(contents.equals("5651400")){
            mIntent=new Intent(this,SettingsActivity.class);
            startActivity(mIntent);
            mMsgInputDialog.cancel();
        }else{
            Toast.makeText(this,"密码有误",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
//        SQLiteStudioService.instance().stop();
        CartList.newInstance(this).getList().clear();
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //TODO something
            if(mClear&&!TextUtils.isEmpty(Users.pad)){
                ClearDialogFragment fragment = ClearDialogFragment.newInstance(Users.pad,Users.YHBH,Users.YHMC);
                fragment.show(getSupportFragmentManager(),null);
            }else{
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        String password = mEtPassword.getText().toString().trim();
        mEdit.putBoolean("savepassword",b);
        mEdit.putString("password",password);
        mEdit.commit();
    }
}
